package com.sale.succ.login;

import static com.sale.succ.utils.TraderHelper.getLabel;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.sale.succ.components.MessDialog;
import com.sale.succ.forms.MainForm;
import com.sale.succ.objects.Session;
import com.sale.succ.system.TradeMarketException;
import com.sale.succ.system.ftp.FTPException;
import com.sale.succ.system.ftp.FTPProcessing;
import com.sale.succ.system.txt.ObjectsProvider;
import com.sale.succ.system.txt.TXTProcessing;
import com.sale.succ.utils.DateFormatter;
import com.sale.succ.utils.Logger;
import com.sale.succ.utils.SystemConstants;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.ui.Button;
import eve.ui.CellPanel;
import eve.ui.Input;
import eve.ui.InputStack;
import eve.ui.ScrollableHolder;
import eve.ui.VerticalScrollPanel;
import eve.ui.data.Editor;

public class LoginScreen extends Editor {
	private Button loginButton;
	private Input userNameInput;
	private Input passwordInput;
	private MessDialog loadingDialog;
	//private Date begin = DateFormatter.stringToDate("22.03.2010");
	//private String protFile = TraderHelper.getCurrentDir() + "/../../Windows/protsz.dll";
	
	private Input getUserNameInput(InputStack stack){
		if(userNameInput == null){
			userNameInput = stack.addInput(TraderHelper.getLabel(TraderConstants.USER_NAME), "");
		}
		return userNameInput;
	}
	
	// Convenience method to add a password field to an input stack.
	private Input addPasswordField(InputStack stack) {
		if(passwordInput == null){
			passwordInput = stack.addInput(TraderHelper.getLabel(TraderConstants.PASSWORD), "");
			passwordInput.isPassword = true;
		}
		return passwordInput;
	}
	
	private Button getLofinButton() {
		if (loginButton == null) {
			loginButton = new Button(TraderHelper.getLabel(
					TraderConstants.LOGIN),
					SystemConstants.DEFAULT_PATH + SystemConstants.SMALL_LOGIN_BUTTON);
			loginButton.setAction(TraderConstants.LOGIN_ACTION);
		}
		return loginButton;
	}

	private InputStack getInputStack(CellPanel destination, String text, CellPanel subPanel) {
		if (destination == null){
			destination = this;
		}
		if (subPanel != null){
			destination = subPanel;
		}
		InputStack is = new InputStack();
		destination.addLast(is).setControl(HCENTER).setCell(HSTRETCH);
		if (text != null) {
			if (subPanel != null){
				subPanel.setText(text);
			}
			else{
				is.setText(text);
			}
		}
		return is;
	}

	// Setup the LoginScreen.
	public LoginScreen() {
		try{
			/*
			if ((new Long(Math.abs(new Date().getTime() - begin.getTime()))) >= new Long(
					1000 * 60 * 60 * 24 * 7)) {
				new MessDialog(TraderHelper
						.getLabel(TraderConstants.LICENSE_ENDED)).execute();
				System.exit(0);
			}
			if (!new File(protFile).exists()) {
				System.exit(0);
			}
			*/
			
			title = TraderHelper.getLabel(TraderConstants.LOGIN_FORM);
			CellPanel data = new CellPanel();
			VerticalScrollPanel vsp = new VerticalScrollPanel(new ScrollableHolder(data));
			addLast(vsp);
			data.backGround = TraderConstants.BUTTON_BGR;
	
			InputStack is = getInputStack(data, TraderHelper.getLabel(TraderConstants.LOGIN_FORM), null);
			is.inputLength = 20;
			addField(getUserNameInput(is), "");
			addField(addPasswordField(is), "");
			addButton(getLofinButton());
			addField(getLofinButton(), "login");
			doButtons(CANCELB);
		}catch(Exception ex){
			Logger.error(ex.toString());
		}
	}
	
	public boolean handleAction(String action) {
		if (action.equals(TraderConstants.LOGIN_ACTION)) {
			try{
				if(userNameInput != null && passwordInput != null){
					loadingDialog = new MessDialog(getLabel(TraderConstants.LOADING), MessDialog.NOB);
					loadingDialog.exec();
					try {
						ObjectsProvider.getInstance().clearCollections();
						Session.getInstance().clearAllMarks();
						Session.getInstance().setLogin(userNameInput.getText());
						Session.getInstance().setPassword(passwordInput.getText());
						String zipName = DateFormatter.dateTimeToString(new Date(), "") + "_" + SystemConstants.ORDER_ZIP;
						FTPProcessing ftp;
						try {
							/*-- FTP --*/
							ftp = new FTPProcessing(Session.getInstance().getLogin(), Session.getInstance().getPassword());
							ftp.setLocalDir(SystemConstants.TRADE_ZIP_DIR);
							ftp.ftpDownload(SystemConstants.TRADE_ZIP);
							if(TXTProcessing.createZip(SystemConstants.ORDERS_DIR + File.separator + zipName, SystemConstants.ORDERS_DIR)){
								ftp.setLocalDir(SystemConstants.ORDERS_DIR);
								ftp.ftpUpload(zipName);
								TXTProcessing.deleteOrderFiles(SystemConstants.ORDERS_DIR);
							}
							ftp.closeFTP();
							/*---------*/
							File file = new File(SystemConstants.TRADE_ZIP_DIR + File.separator + SystemConstants.RESTS_FILE);
							if(file.exists()){
								file.delete();
							}
							ObjectsProvider.getInstance().getTradeMarkCollection();
							ObjectsProvider.getInstance().getProductCollection();
						} catch (FTPException ex) {
							new TradeMarketException(ex.getMessage(), TraderHelper.getLabel(TraderConstants.FTP_DOWNLOAD_ABORTED));
						} catch (IOException ex) {
							new TradeMarketException(ex.getMessage(), TraderHelper.getLabel(TraderConstants.FTP_DOWNLOAD_ABORTED));
						}
					}
					finally {
						loadingDialog.close(0);
					}
				}
				else{
					throw new TradeMarketException(TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
				}
				new MainForm().execute();
			}
			catch(Exception ex){
				Logger.error(ex.toString());
			}
			return true;
		}
		return super.handleAction(action);
	}
}